/*
 * @Author: Wangtao
 * @Date: 2020-10-19 17:38:20
 * @LastEditors: Wangtao
 * @LastEditTime: 2020-10-19 17:39:19
 */
const clickOutCtx = '@@clickOutCtx'

export default {
  bind(
    el: {
      [x: string]: { documentHandler: (e: any) => false | undefined; methodName: any; bindingFn: any }
      contains: any
    },
    binding: { expression: any; value: any },
    vNode: { context: { [x: string]: (arg0: any) => void } }
  ) {
    const documentHandler = function (e: { target: any }) {
      if (!vNode.context || el.contains(e.target)) {
        return false
      }
      if (binding.expression) {
        vNode.context[el[clickOutCtx].methodName](e)
      } else {
        el[clickOutCtx].bindingFn(e)
      }
    }
    el[clickOutCtx] = {
      documentHandler,
      methodName: binding.expression,
      bindingFn: binding.value
    }
    setTimeout(() => {
      document.addEventListener('click', documentHandler)
    }, 0)
  },
  update(el: any, binding: { expression: any; value: any }) {
    el[clickOutCtx].methodName = binding.expression
    el[clickOutCtx].bindingFn = binding.value
  },
  unbind(el: { [x: string]: { documentHandler: (this: Document, ev: MouseEvent) => any } }) {
    document.removeEventListener('click', el[clickOutCtx].documentHandler)
  }
}
